package com.psycho.sys.api.controller;

import java.time.LocalDateTime;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psycho.sys.api.common.Result;
import com.psycho.sys.api.entity.Counselor;
import com.psycho.sys.api.entity.User;
import com.psycho.sys.api.service.UserService;
import com.psycho.sys.api.vo.UserVO;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 用户管理接口
 */
@Tag(name = "用户管理接口")
@RestController
@RequestMapping("/api/users")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Operation(summary = "分页查询用户列表")
    @GetMapping("/page")
    public Result<Page<UserVO>> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "真实姓名") @RequestParam(required = false) String realName,
            @Parameter(description = "手机号") @RequestParam(required = false) String phone,
            @Parameter(description = "用户类型") @RequestParam(required = false) Integer userType,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        try {
            // 创建分页对象
            Page<User> page = new Page<>(current, size);

            // 构建查询条件
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                    .like(StringUtils.isNotEmpty(username), User::getUsername, username)
                    .like(StringUtils.isNotEmpty(realName), User::getRealName, realName)
                    .like(StringUtils.isNotEmpty(phone), User::getPhone, phone)
                    .eq(userType != null, User::getUserType, userType)
                    .eq(status != null, User::getStatus, status)
                    .orderByDesc(User::getCreateTime);

            // 执行分页查询
            Page<User> userPage = userService.page(page, wrapper);

            // 转换为VO对象
            Page<UserVO> voPage = new Page<>();
            BeanUtils.copyProperties(userPage, voPage, "records");

            // 转换记录
            voPage.setRecords(userPage.getRecords().stream()
                    .map(user -> {
                        UserVO vo = new UserVO();
                        BeanUtils.copyProperties(user, vo);
                        return vo;
                    })
                    .collect(Collectors.toList()));

            return Result.success(voPage);
        } catch (Exception e) {
            return Result.error("查询用户列表失败：" + e.getMessage());
        }
    }

    @Operation(summary = "获取用户详情")
    @GetMapping("/{id}")
    public Result<User> getById(@Parameter(description = "用户ID") @PathVariable Long id) {
        return Result.success(userService.getById(id));
    }

    @Operation(summary = "新增用户")
    @PostMapping("/add")
    @Transactional
    public Result<Boolean> save(@RequestBody User user) {
        try {
            User existingUser = userService.findByUsername(user.getUsername());
            if (existingUser != null) {
                return Result.error("用户名已存在");
            }

            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode("123456");
            user.setPassword(encodedPassword);
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setStatus(1);
            boolean userSaved = userService.save(user);

            if (userSaved && user.getUserType() == 1) {
                Counselor counselor = new Counselor();
                counselor.setUserId(user.getId());
                counselor.setStatus(1);
                counselor.setCreateTime(LocalDateTime.now());
                counselor.setUpdateTime(LocalDateTime.now());
                counselor.setTitle("心理咨询师");
                userService.saveCounselor(counselor);
            }

            return Result.success(userSaved);
        } catch (Exception e) {
            return Result.error("新增用户失败：" + e.getMessage());
        }
    }

    @Operation(summary = "修改用户")
    @PutMapping("/{id}")
    public Result<Boolean> update(
            @Parameter(description = "用户ID") @PathVariable Long id,
            @RequestBody User user) {
        try {
            user.setId(id);
            user.setUpdateTime(LocalDateTime.now());
            return Result.success(userService.updateById(user));
        } catch (Exception e) {
            return Result.error("修改用户失败：" + e.getMessage());
        }
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    public Result<Boolean> remove(@Parameter(description = "用户ID") @PathVariable Long id) {
        try {
            return Result.success(userService.removeById(id));
        } catch (Exception e) {
            return Result.error("删除用户失败：" + e.getMessage());
        }
    }
}